package com.qingke.ocr.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.qingke.ocr.pojo.User;

public class OCRDAO {
	private String driverStr="com.mysql.jdbc.Driver";
	private String connStr="jdbc:mysql://localhost:3306/servlet_login?useUnicode=true&characterEncoding=utf-8&useSSL=false";
	private String sqlUsername="zjy";
	private String sqlPassword="123456";
	
    private Connection conn=null;		
    private String sql;
    private PreparedStatement ps=null;
    private ResultSet rs=null;  
    
    {
    	try {
			Class.forName(driverStr);
			conn = DriverManager.getConnection(connStr,sqlUsername,sqlPassword);
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
    }
    
    public boolean isUsernameExist(String username){
    	sql="select * from user where username=?";
    	try {
			ps=conn.prepareStatement(sql);
			ps.setString(1,username);
			rs=ps.executeQuery();
			if(rs!=null&&rs.next()){
				return true;
			}
			return false;
		} catch (SQLException e) {
			e.printStackTrace();
			return false;
		}
    }
    
    public User login(String username,String password){
    	sql="select * from user where username=? and password=?";
    	try {
			ps=conn.prepareStatement(sql);
			ps.setString(1,username);
			ps.setString(2,password);
			rs=ps.executeQuery();
			if(rs!=null&&rs.next()){
				User user=new User();
				user.setUsername(username);
				user.setNickname(rs.getString("nickname"));
				return user;
			}
			return null;
		} catch (SQLException e) {
			e.printStackTrace();
			return null;
		}
    	
    }
    
    public boolean register(String username,String password,String nickname){
    	if(isUsernameExist(username)){
    		return false;
    	}
    	sql="insert into user(username,password,nickname) values(?,?,?);";
    	try {
			ps=conn.prepareStatement(sql);
			ps.setString(1,username);
			ps.setString(2,password);
			ps.setString(3,nickname);
			int count=ps.executeUpdate();
			if(count>0)
				return true;
			else
				return false;
		} catch (SQLException e) {
			e.printStackTrace();
			return false;
		}
    }
}
